﻿using CommonTool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tool;

namespace AutoMachine
{
    internal partial class Frm_TcpClient : Form
    {

        #region 窗体实例化
        /// <summary>
        /// 窗体对象实例化
        /// </summary>
        private static Frm_TcpClient _instance;
        internal static Frm_TcpClient Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new Frm_TcpClient();
                return _instance;
            }
        }
        #endregion


        internal Frm_TcpClient()
        {
            InitializeComponent();
        }
        /// <summary>
        ///通讯用Socket 
        /// </summary>
        Socket socketclient = null;
        public delegate void DataReceiveHandler(string str);
        public event DataReceiveHandler DataReceiveEvent;
        /// <summary>
        /// 接收消息的线程
        /// </summary>
        private static Thread th_receive = null;
        private static string IP = "192.168.1.3";
        private static string port = "64000";
        //运行标志位
        private bool IsRunning = true;
        public string ReceiveMessage="";

        /// <summary>
        /// 读取IP和Port
        /// </summary>
        private void Get()
        {
            //客户端IP地址和端口号
            this.tbx_ip.Text = IP;
            this.tbx_port.Text = port;
        }

        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="msg"></param>
        public void Send(string msg)
        {
            try
            {
                byte[] buffer = Encoding.Default.GetBytes(msg);
                //socketclient.Send(buffer);
                //LogView.GetInstance().ShowLog(LogView.LogType.Oper, "网口发送:" + msg);//保存Log
                //ShowMsg("->: " + tbx_sendMessage.Text.Trim());
            }
            catch (Exception ex )
            {
                LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                MessageBox.Show(ex.Message);
            }


        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        public void Connect()
        {
            try
            {
                Again:
                if (btn_connect.Text == "连接")
                {
                    IPAddress address = IPAddress.Parse(IP);

                    IPEndPoint Ipe = new IPEndPoint(address, int.Parse(port));

                    socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    try
                    {
                  socketclient.Connect(Ipe);//连接
                    }
                    catch 
                    {

                        if (MessageBox.Show("连接失败，可能是第三方通讯设备未正常运行，请在第三方通讯设备正常运行后点击确定，或直接点击取消放弃连接。", "提示：", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            goto Again;
                        }
                    }
                    if (socketclient.Connected)//已连接上
                    {
                        lbl_connectStatu.Text = "已连接";
                        lbl_connectStatu.ForeColor = Color.Green;
                        th_receive = new Thread(ReceiveMsg);
                        th_receive.IsBackground = true;//后台线程
                        th_receive.Start();
                      //  btn_connect.Text = "断开";
                        tbx_ip.Enabled = false;
                        tbx_port.Enabled = false;
                    }
                  
                   
                }
            }
            catch (Exception ex)
            {
                LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        public void ReceiveMsg()
        {
            try
            {
                //定义一个2M缓冲区
                byte[] buffer = new byte[1024*1024*2];
                while (IsRunning)
                {
                    int length = 0;
                    try
                    {
                        length = socketclient.Receive(buffer);
                    }
                    catch (Exception ex)
                    {
                        LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                        MessageBox.Show(ex.Message);
                    }
                    string result = Encoding.Default.GetString(buffer, 0, length);
                    if (length > 0)
                    {
                        ReceiveMessage = result;
                        DataReceiveEvent(result);
                        //ShowMsg("<-:" + result);

                    }
                    else
                    {
                        if (socketclient != null)
                        {
                            try
                            {
                                socketclient.Disconnect(false);
                                socketclient.Close();//关闭
                            }
                            catch { }
                        }
                        lbl_connectStatu.Text = "已断开";
                        lbl_connectStatu.ForeColor = Color.Red;
                        btn_connect.Text = "连接";
                        tbx_ip.Enabled = true;
                        tbx_port.Enabled = true;
                        return;
                    }
                }



            }
            catch (Exception ex )
            {
                LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                MessageBox.Show(ex.Message);
            }


        }



        private void FrmTcpClient_Load(object sender, EventArgs e)
        {
            Get();//获取IP地址和端口号

        }

        //连接按钮
        private void btn_connect_Click(object sender, EventArgs e)
        {
            Connect();
        }

        //发送按钮
        private void btn_send_Click(object sender, EventArgs e)
        {
            try
            {
                if (socketclient == null || !socketclient.Connected)
                {
                    MessageBox.Show("未建立连接");
                    return;
                }
                if (tbx_sendMessage.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("不能发送空内容");
                    return;
                }
                Send(tbx_sendMessage.Text.Trim());
            }
            catch (Exception ex )
            {
                LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                MessageBox.Show(ex.Message);
            }
        }


        //清空记录
        private void lnk_clearLog_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tbx_log.Clear();
        }

        private void FrmTcpClient_FormClosing(object sender, FormClosingEventArgs e)
        {
          
            //IsRunning = false;
        }
    }
}
